package webSocket;

import org.apache.log4j.Logger;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * Created by zhoub on 2020/4/8.
 */
public class WebSocketClientTest {

    private static Logger logger = Logger.getLogger(WebSocketClientTest.class);
    public static WebSocketClient client;
    public static void main(String[] args) {

        try {
            //建立长连接
            int port = 8081;
            ServerSocket serverSocket = new ServerSocket(port);
            final Socket socket = serverSocket.accept();
            OutputStream os = socket.getOutputStream();
            client = new WebSocketClient(new URI("ws://localhost:9090/eqm/websocket?ticket=eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJwYW54aW5taW4iLCJhdWRpZW5jZSI6IkFVRElFTkNFX1dFQiIsImNyZWF0ZWQiOjE1ODYzMTEwNzQ3ODAsInVzZXJuYW1lQ24iOiLmvZjmlrDmsJEiLCJleHAiOjE1ODY5MTEwNzQsInVzZXJpZCI6Ijk3MTgxIn0.H6MUrOItVDhRqXUPjeNBnVN5i6Q_jL1-UWamGpqAQRSuQBy_-ASS05FS4cptWJdiC1rbILcBlAP0dqcH7_N-Jw"),new Draft_6455()) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    System.out.println("握手成功");
                }

                @Override
                public void onMessage(String msg) {
                    System.out.println("收到消息=========="+msg.length());
                    msg = msg.substring(1,msg.length()-1);
                    msg = msg.replaceAll("\\\\u","\\u");
                    msg = unicodeToStr(msg);
                    try {
                        byte[] bs = msg.getBytes("ISO-8859-1");
                        os.write(bs);
                        os.flush();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    if(msg.equals("over")){
                        client.close();
                    }

                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    System.out.println("链接已关闭");
                }

                @Override
                public void onError(Exception e){
                    e.printStackTrace();
                    System.out.println("发生错误已关闭");
                }
            };
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        client.connect();
        System.out.println(client.getDraft());
        while(!client.getReadyState().equals(ReadyState.OPEN)){
            System.out.println("正在连接...");
        }
        //连接成功,发送信息
        client.send("哈喽,连接一下啊");
    }

    /**
     * 字符串转unicode
     * @param str
     * @return
     */
    public static String str2Unicode(String str) {
        str = (str == null ? "" : str);
        String tmp;
        StringBuffer sb = new StringBuffer(1000);
        char c;
        int i, j;
        sb.setLength(0);
        for (i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            sb.append("\\u");
            j = (c >>> 8); // 取出高8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);
            j = (c & 0xFF); // 取出低8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);
        }
        return sb.toString();
    }

    /**
     * 字符串转unicode
     *
     * @param str
     * @return
     */
    public static String strToUnicode(String str) {
        StringBuilder sb = new StringBuilder();
        char[] c = str.toCharArray();
        for (int i = 0; i < c.length; i++) {
            sb.append("\\u" + Integer.toHexString(c[i]));
        }
        return sb.toString();
    }

    /**
     * unicode转字符串
     *
     * @param unicode
     * @return
     */
    public static String unicodeToStr(String unicode) {
        StringBuilder sb = new StringBuilder();
        String[] hex = unicode.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            int index = Integer.parseInt(hex[i], 16);
            sb.append((char) index);
        }
        return sb.toString();
    }



}
